<?php
namespace App\Admin\Controllers\OverSeasIn;

use App\Admin\Ajax\OverSeasIn\OSAjax;
use App\Exporter\OverSeasIn\OSExporter;
use App\Exporter\OverSeasIn\OSTrackingNoExporter;
use App\Models\Basics\SysArea;
use App\Models\OverSeasIn\Delivery;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasIn\DeliveryBox;
use App\Models\Sys\Logs;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Request;
use Illuminate\Http\Request as FRequest;
use Maatwebsite\Excel\Facades\Excel;

class OSController extends AdminController{

    protected $title = 'CN至海外仓(中转)-发货单';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'delivery_no' => null,
        'warehouse_id' => null,
        'area_id' => null,
        'seller_id' => null,
        'status' => null,
        'logistics_status' => null,
        'transport_status' => null,
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['delivery_no'] = $this->filters['delivery_no'];
        $filtersBlade['warehouse_id'] = getOptions(Warehouse::options(),$this->filters['warehouse_id']);
        $filtersBlade['area_id'] = getOptions(SysArea::options(),$this->filters['area_id']);
        $filtersBlade['seller_id'] = getOptions(User::getSellerOptions(),$this->filters['seller_id']);
        $filtersBlade['status'] = getOptions(Delivery::$_status,$this->filters['status']);
        $filtersBlade['logistics_status'] = getOptions(Delivery::$_logisticsStatus,$this->filters['logistics_status']);
        $filtersBlade['transport_status'] = getOptions(Delivery::$_transportStatus,$this->filters['transport_status']);
        $filtersBlade['sku'] = $this->filters['sku'];
        return view('overseas-in.os.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        //海外仓-发货
        $query = Delivery::query()
            ->where('delivery_type', Delivery::OS_DELIVERY_TRANSFER) //中转
            ->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('delivered_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('delivered_at','<=',$filter.' 23:59:59');
            }
            if(in_array($field,['delivery_no','warehouse_id','area_id','seller_id','status','logistics_status','transport_status'])){
                $query->where($field,$filter);
            }
            if($field == 'sku'){
                $query->whereHas('detail.sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new OSAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function trace(FRequest $request){
        $action = $request->get('action');
        $param = $request->get('param');
        $file = $request->file('source_file');
        $trace = new OSAjax();
        return $param ? call_user_func([$trace,$action],$file,$param) : call_user_func([$trace,$action],$file);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new OSAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function edit($id, Content $content)
    {
        $delivery = Delivery::query()->findOrFail($id);
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body(view('overseas-in.os-edit.index', compact('id','delivery')));
    }

    public function update($id)
    {
        $delivery = Delivery::query()->findOrFail($id);
        $name = Request::get('name');
        $value = Request::get('value');
        $delivery->{$name} = $value;
        $flag = $delivery->save();
        if($flag){
            //批次号
            if($name == 'batch_no'){
                DeliveryBox::query()
                    ->where('delivery_no' , $delivery->delivery_no)
                    ->update(['batch_no' => $delivery->batch_no]);
            }
            return response()->json(['status' => true, 'message' => '操作成功']);
        }else{
            return response()->json(['status' => false, 'message' => '操作失败']);
        }
    }

    protected function detail($id)
    {
        $delivery = Delivery::query()->findOrFail($id);
        $logs = Logs::getLogs('os-in-delivery',$id);
        return view('overseas-in.os-detail.index', compact('id','delivery','logs'));
    }

    public function download($id)
    {
        $delivery = Delivery::query()->findOrFail($id);
        return Excel::download(new OSExporter($delivery),$delivery->delivery_no.'.xlsx');
    }

    public function downloadTrackingNo($id)
    {
        $delivery = Delivery::query()->findOrFail($id);
        return Excel::download(new OSTrackingNoExporter($delivery),$delivery->delivery_no.'.xlsx');
    }

    //装箱信息
    protected function box($id, Content $content)
    {
        $delivery = Delivery::query()->findOrFail($id);
        return $content
            ->title($this->title())
            ->description('编辑')
            ->body(view('overseas-in.os-box.index', compact('id','delivery')));
    }
}
